package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.aifeng.base.BaseActivity
import com.aifeng.base.addItems
import com.aifeng.base.loadRoundedImage
import com.aifeng.base.setHtmlSmall
import com.aifeng.common_ui.base.*
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.WebActivity
import com.aifeng.hassan_food.sale.ConfirmPayActivity
import com.aifeng.model.BaseUrl
import com.aifeng.model.CommonData
import com.aifeng.model.OrderData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.getExtra
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.activity_order_detail.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class OrderDetailActivity : BaseActivity() {

    private var mData: OrderData? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_detail)
        initTitle(title = "订单详情")

        getData()
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        order_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(baseContext)
            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_shop_inner_list_80) { inner, jector ->

                    val index = mList.indexOf(inner)
                    val isLast = index == mList.size - 1

                    jector.text(R.id.item_shop_name, inner.goodsname)
                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                        .text(
                            R.id.item_shop_price,
                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                        )
                        .text(R.id.item_shop_num, "x${inner.num}")
                        .with<ImageView>(R.id.item_shop_img) { view ->
                            val imgs = inner.goodimg.split(",")
                            view.loadRoundedImage(url = imgs[0].scaleImage())
                        }
                        .visibility(
                            R.id.item_shop_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_shop_divider,
                            if (isLast) View.GONE else View.VISIBLE
                        )
                }
                .attachTo(this)
        }

        order_step.oneClick {
            mData?.let {
                if (it.expressno.isNotEmpty()
                    && order_step_hint2.isVisble()
                )
                    startActivity<OrderExpressActivity>("num" to it.expressno)
                else toast("暂无物流信息！")
            }
        }
        order_service.oneClick { startActivity<WebActivity>("title" to "在线客服") }

        order_bt01.oneClick {
            mData?.let {
                when (it.state) {
                    "0" -> cancelOrder(it.id)
                    "2" -> {
                        if (it.expressno.isNotEmpty()
                            && order_step_hint2.isVisble()
                        ) startActivity<OrderExpressActivity>("num" to it.expressno)
                        else toast("暂无物流信息！")
                    }
                    "7", "99" -> deleteOrder(it.id)
                    else -> {}
                }
            }
        }

        order_bt02.oneClick {
            mData?.let {
                when (it.state) {
                    "0" -> {
                        startActivity<ConfirmPayActivity>(
                            "orderNo" to it.orderno,
                            "price" to it.paytotal,
                            "express" to it.expressfee,
                            "orderId" to it.id,
                            "orderIndex" to intent.getExtra("index")
                        )
                    }
                    "2" -> confirmOrder(it.id)
                    "99" -> {
                        if (it.expressno.isNotEmpty()
                            && order_step_hint2.isVisble()
                        ) startActivity<OrderExpressActivity>("num" to it.expressno)
                        else toast("暂无物流信息！")
                    }
                    else -> {}
                }
            }
        }

        observe("orderDetail") { getData() }
    }

    private fun confirmOrder(orderId: String) {
        showHintDialog(
            title = "确认收货",
            hint = "确认已收到购买的商品？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.confirmGoods,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        LiveEventBus.get("orderList").post("confirm,${intent.getExtra("index")}")
                        getData()
                    }
                )
        }
    }

    private fun cancelOrder(orderId: String) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.cancelOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        LiveEventBus.get("orderList").post("cancel,${intent.getExtra("index")}")
                        getData()
                    }
                )
        }
    }

    private fun deleteOrder(orderId: String) {
        showHintDialog(
            title = "删除订单",
            hint = "确定要删除订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.delOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        LiveEventBus.get("orderList").post("delete,${intent.getExtra("index")}")
                        ActivityStack.screenManager.popActivities(this::class.java)
                    }
                )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().orderDetail(
            intent.getExtra("id"),
            getString("userId")
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.clear()
                    mList.addItems(it.goodlist)
                    mAdapter.updateData(mList)

                    order_shop.text = it.shopname
                    mData = it.order
                    setData()
                }
            )
    }

    @SuppressLint("SetTextI18n")
    private fun setData() {
        mData?.let {
            order_name.text = it.receiver
            order_tel.text = it.phone
            order_adress.text = it.address

            order_total.text = "¥ ${it.total.formatDecimal()}"
            order_plus.text = "— ¥ ${(it.total.toNotDouble() - it.paytotal.toNotDouble()).formatDecimal()}"
            order_yun.text = "+ ¥ ${it.expressfee.formatDecimal()}"
            order_pay.text = "¥ ${(it.paytotal.toNotDouble() + it.expressfee.toNotDouble()).formatDecimal()}"
            order_code.text = "订单编号：${it.orderno}"

            order_time1.text = "创建时间：${it.createDate.toNotLong().getTimeString()}"
            order_time2.text = "付款时间：${it.paydate.toNotLong().getTimeString()}"
            order_time3.text = "发货时间：${it.senddate.toNotLong().getTimeString()}"
            order_time4.text = "成交时间：${it.finishdate.toNotLong().getTimeString()}"

            if (it.state == "99") {
                order_bt02.backgroundResource = R.drawable.rec_bg_ova_white_stroke_a3a3a3
                order_bt02.textColor = Color.parseColor("#505050")
            } else {
                order_bt02.backgroundResource = R.drawable.rec_bg_ova_white_stroke_red
                order_bt02.textColor = getColorEx(R.color.colorAccent)
            }

            when (it.state) {
                "0" -> {
                    order_left.gone()
                    order_step.gone()
                    order_time1.visible()
                    order_time2.gone()
                    order_time3.gone()
                    order_time4.gone()
                    order_bt01.visible()
                    order_bt02.visible()

                    order_hint.text = "等待付款"
                    order_back.backgroundResource = R.mipmap.icon_bg09
                    order_bt01.text = "取消订单"
                    order_bt02.text = "去支付"
                }
                "1" -> {
                    order_left.gone()
                    order_step.gone()
                    order_time1.visible()
                    order_time2.visible()
                    order_time3.gone()
                    order_time4.gone()
                    order_bt01.gone()
                    order_bt02.gone()

                    order_hint.text = "等待卖家发货"
                    order_back.backgroundResource = R.mipmap.icon_bg10
                }
                "2" -> {
                    order_left.gone()
                    order_step.visible()
                    order_time1.visible()
                    order_time2.visible()
                    order_time3.visible()
                    order_time4.gone()
                    order_bt01.visible()
                    order_bt02.visible()

                    order_hint.text = "卖家已发货"
                    order_back.backgroundResource = R.mipmap.icon_bg11
                    order_bt01.text = "查看物流"
                    order_bt02.text = "确认收货"
                }
                "7" -> {
                    order_left.gone()
                    order_step.gone()
                    order_time1.visible()
                    order_time2.gone()
                    order_time3.gone()
                    order_time4.gone()
                    order_bt01.visible()
                    order_bt02.gone()

                    order_hint.text = "交易取消"
                    order_back.backgroundResource = R.drawable.rec_bg_red_r0
                    order_bt01.text = "删除订单"
                }
                "99" -> {
                    order_left.gone()
                    order_step.visible()
                    order_time1.visible()
                    order_time2.visible()
                    order_time3.visible()
                    order_time4.visible()
                    order_bt01.visible()
                    order_bt02.visible()

                    order_hint.text = "交易完成"
                    order_back.backgroundResource = R.mipmap.icon_bg12
                    order_bt01.text = "删除订单"
                    order_bt02.text = "查看物流"
                }
            }

            if (order_step.isVisble() && it.expressno.isNotEmpty()) {
                getViewModel().expressList(it.expressno, false)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByFinally(
                        event = getViewModel(),
                        onSuccess = { items ->
                            if (items.isNotEmpty()) {
                                order_step_hint1.text = items[0].opeRemark
                                order_step_hint2.text = items[0].opeTime.replace("/", "-")
                                order_step_hint2.visible()
                            } else {
                                order_step_hint1.text = "暂无物流信息"
                                order_step_hint2.gone()
                            }
                        }
                    )
            }
        }
    }

}
